import { brandList } from '@/apis';
import { IBrand } from '@/types';
import { useMap } from 'ahooks';
import { useCallback, useEffect } from 'react';
import { atom, useRecoilState } from 'recoil';

interface IBrandState {
    /**
     * if inited
     */
    init: boolean;
    /**
     * brand list
     */
    data: IBrand[];
}

/**
 * brand data
 */
const brandState = atom<IBrandState>({
    key: 'brand',
    default: {
        init: false,
        data: []
    }
});

/**
 * 品牌列表
 */
function useBrand() {
    const [val, setVal] = useRecoilState(brandState);
    const [brandMap, { set }] = useMap<number, string>();

    const update = useCallback(
        () => {
            brandList().then(res => {
                setVal({
                    init: true,
                    data: res.data
                });
            });
        }, 
        []
    );

    useEffect(() => {
        if (!val?.init) {
            update();
        }
    }, []);

    useEffect(() => {
        val.data.forEach(d => {
            set(d.id, d.brand);
        })
    }, [val.data]);

    const res: [
        IBrand[],
        Map<number, string>,
        () => void
    ] = [
        val.data,
        brandMap,
        update
    ];

    return res;
}


export {
    brandState,
    useBrand
};
